#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
using namespace std;

#define FIFO_NAME "my_fifo"

int main()
{
    // 创建命名管道
    umask(0000);
    if (mkfifo(FIFO_NAME, 0644) == -1)
    {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }

    int fd = open(FIFO_NAME, O_RDONLY);
    char buffer[100];

    while (true) // 读取数据
    {
        int n = read(fd, buffer, sizeof(buffer) - 1);
        if (n == 0)
        {
            cout << "写端关闭" << endl;
            break;
        }
        else if (n < 0)
        {
            cerr << "读取出错:" << strerror(errno) << endl;
            break;
        }
        buffer[n] = 0;
        printf("Reader received: %s\n", buffer);
    }
    close(fd);
    // 删除命名管道
    unlink(FIFO_NAME);

    return 0;
}